#include <iostream>
#include <pthread.h>
#include <unistd.h>
//加锁前，由于多线程执行同一代码，容易将票数减成负数

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//全局锁
//加锁后，多线程执行同一代码就像过独木桥，临界区代码一次只由一个线程执行


int ticket = 1000;

void* Routine(void* arg)
{
    char* id = (char*)arg;
    while(1)
    {
        pthread_mutex_lock(&lock);//加锁
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket: %d\n", id, ticket);
            ticket--;
            pthread_mutex_unlock(&lock);//解锁
        }
        else
        {
            //无论哪种情况都要解锁
            pthread_mutex_unlock(&lock);//解锁
            break;
        }
    }
    return nullptr;
}





int main()
{
    pthread_t tid1, tid2, tid3, tid4;

    pthread_create(&tid1, nullptr, Routine, (void*)"thread-1");
    pthread_create(&tid2, nullptr, Routine, (void*)"thread-2");
    pthread_create(&tid3, nullptr, Routine, (void*)"thread-3");
    pthread_create(&tid4, nullptr, Routine, (void*)"thread-4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);


    return 0;
}